﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Specialized;
using System.Threading;
using System.Windows.Threading;

namespace agilecards.Model
{
    public class AutoSaver : INotifier
    {
        public AutoSaver(ICardCollection cardCollection, ICardCollectionPersistor cardPersistor)
        {
            _cardCollection = cardCollection;
            _cardPersistor = cardPersistor;
            //cardCollection.Cards.CollectionChanged += new NotifyCollectionChangedEventHandler(Cards_CollectionChanged);

            DispatcherTimer autoSaveTimer = new DispatcherTimer();
            autoSaveTimer.Interval = new TimeSpan(0, 0, 0, AUTOSAVE_INTERVAL_IN_SECONDS);
            autoSaveTimer.Tick += new EventHandler(autoSaveTimer_Tick);
            autoSaveTimer.Start();
        }

        void autoSaveTimer_Tick(object sender, EventArgs e)
        {
            OnNotifyOccured(new NotifyOccuredEventArgs() { Message = "Saving..." });
            _cardPersistor.Save(_cardCollection);
            OnNotifyOccured(new NotifyOccuredEventArgs() { Message = "Save complete" });
        }


        #region INotifier Members
        public event EventHandler<NotifyOccuredEventArgs> NotifyOccured;
        protected void OnNotifyOccured(NotifyOccuredEventArgs e)
        {
            if (this.NotifyOccured != null)
            {
                this.NotifyOccured(this, e);
            }

        }
        #endregion

        ICardCollection _cardCollection;
        ICardCollectionPersistor _cardPersistor;
        const int AUTOSAVE_INTERVAL_IN_SECONDS = 5;
    }
}
